package com.bjsxt.userCenter.filter;

import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bjsxt.userCenter.common.util.ConstatFinalUtil;
import com.bjsxt.userCenter.common.util.HttpUtil;

/**
 * 过滤器
 * @author zhanghuan
 *
 */
public class AuthFilter implements Filter
{

	@Override
	public void destroy()
	{
		
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
			throws IOException, ServletException
	{
		System.out.println("----doFilter----");
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
		HttpSession session = request.getSession();
		
		/*先检查session中是否有值*/
		JSONObject adminsJSON = (JSONObject) session.getAttribute("admins");
		if(adminsJSON!=null)
		{
			chain.doFilter(request, response);
			return;
		}
		
		/* token
		 * 如果有多个token:
		 * 取最后一个
		 *  */
		String[] tokens = request.getParameterValues("token");
		String token ="";
		if(tokens!=null)
		{
			token = tokens[tokens.length-1];
		}
		/* 传入了token
		 * 就是从用户中心跳转过来的
		 *  */
		if(!"".equalsIgnoreCase(token))
		{
			/* 到token的颁发中心,去验证一下是不是你颁发的
			 * 验证token的接口,我们今天上午写过了
			 *  */
			
			HttpUtil httpUtil = new HttpUtil();
			/*
			 * 拼装上行的json  加密参数;sha256(version+pubKey+私钥)忽略不拼装
			 */
			JSONObject requestJSON = new JSONObject();
			requestJSON.put("version", "1");
			
			JSONObject dataJSON = new JSONObject();
			dataJSON.put("token", token);
			requestJSON.put("data", dataJSON);
			
			/* 拼装url */
			/*String urlStr ="http://localhost:8080/userCenter-back/outer/json/verfiyToken.htm?json={%22version%22:%221%22,%22date%22:{%22token%22:%225f37d906-90cd-427e-96d5-320e761ee6c7%22}}";*/
			String url =ConstatFinalUtil.CONFIG_JSON.getString("userCenter.back.verifyToken.url");
			String params = "?json="+requestJSON.toJSONString();
			url += params;
			System.out.println("-----url----"+url);
			String result = httpUtil.methodGet(url);
			System.out.println(result+"=======================");
			
			/**
			 * 处理返回值
			 * 解析成json
			 * 
			 */
			JSONObject resultJSON = (JSONObject) JSON.parse(result);
			/**
			 * code：0成功
			 * 
			 */
			if(resultJSON !=null && "0".equalsIgnoreCase(resultJSON.getString("code")))
			{
				JSONObject  dateResJSON = (JSONObject) resultJSON.get("data");
				adminsJSON  = dateResJSON.getJSONObject("admins");
				/**
				 * 将token的相关信息存储到客户端的session中
				 */
				session.setAttribute("admins", adminsJSON);
				chain.doFilter(request, response);
				return;
			}
			
		}
		
		/* 需要登陆
		 * 获取当前访问的URL
		 * 客户端跳转到用户中心的登陆页面,
		 * 把returnUrl带上,同时要加密哟(UrlEncode)
		 *  */
		String returnUrl = request.getRequestURL()+"";
		/*获取?后面的参数*/
		String queryStr = request.getQueryString();
		/*?后面的参数木有了,
		 * 如何获取呢?
		 * */
		if(queryStr!=null)
		{
			returnUrl +="?"+queryStr;
		}
		
		
		System.out.println("====returnUrl======="+returnUrl);
		
		 /* 客户端中转到用户中心
		 * http://xxxx:8080/userscenter-back/login.htm?returnUrl
		 * 
		 * ====returnUrl===http://localhost:10000/userCenter-client/back/AdminsBackServlet?method=main
		 * ===第一次url=====http://localhost:10000/userCenter-back/login.htm?id=1
		 * 拼接上returnUrl后的url==http://localhost:10000/userCenter-back/login.htm?id=1&returnUrl=http://localhost:10000/userCenter-client/back/AdminsBackServlet?method=main
		 * */
		String url = ConstatFinalUtil.CONFIG_JSON.getString("userCenter.back.login.url");
		System.out.println("==========第一次url=========="+url);
		url += "&returnUrl="+URLEncoder.encode(returnUrl, "utf-8");
		System.out.println("==========拼接上returnUrl后的url=========="+url);
		response.sendRedirect(url);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException
	{
		
	}

}
